package com.yupi.springbootinit.manager;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description redis限流服务
 * @Author minify
 * @Date 2023/12/11 23:07
 * @Project mybi-backend
 */
@Component
public class RedisLimiterManager {

    @Resource
    private RedissonClient redissonClient;

    public boolean tryAcquire(String key, int permits, TimeUnit timeout) {
        return redissonClient.getRateLimiter(key).tryAcquire(permits, timeout);
    }

    /**
     * 限流操作
     * 区分不同的限流器，比如不同的用户ID应该分别统计
     */
    public boolean doRateLimit(String key) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        // 限流器初始化：每秒钟产生5个令牌
        rateLimiter.trySetRate(RateType.OVERALL, 5, 1, RateIntervalUnit.DAYS);

        // 每当一个请求来了后请求2个令牌
        //throw new RuntimeException("请求已被限制，请明日尝试！");
        return rateLimiter.tryAcquire(1);
    }

    /**
     * 解除限流
     */
    public boolean releaseRateLimit(String key) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        System.out.println(rateLimiter.isExists());
        // 删除限流器
        return rateLimiter.delete();
    }

}
